﻿using System;
using System.IO;

namespace Grinder.Settings
{
    public sealed class IniSettings : SettingsBase
    {
        public IniSettings(string file)
            : base(file)
        {
            Load();
        }

        public override void Load()
        {
            using (var reader = new StreamReader(new FileStream(File, FileMode.OpenOrCreate, FileAccess.Read)))
            {
                Section currentSection = null;

                while (!reader.EndOfStream)
                {
                    string line = reader.ReadLine().Trim();

                    if (string.IsNullOrEmpty(line)) continue;

                    if (line.StartsWith("[") && line.EndsWith("]"))
                    {
                        currentSection = AddSection(line.Substring(1, line.Length - 2));
                    }
                    else if (currentSection != null)
                    {
                        string[] arr = line.Split(new[] { '=' }, StringSplitOptions.RemoveEmptyEntries);

                        if (arr.Length == 2)
                            currentSection.AddValue(arr[0].Trim(), arr[1].Trim());
                        else if (arr.Length == 1)
                            currentSection.AddValue(arr[0].Trim(), "");
                        else
                            throw new InvalidIniEntryException(line);
                    }
                }
            }
        }

        public override void Save()
        {
            using (var writer = new StreamWriter(new FileStream(File, FileMode.Create, FileAccess.Write)))
            {
                foreach (var section in Sections.Values)
                {
                    writer.WriteLine("\n[{0}]", section.Name);

                    foreach (var keyvalue in section.Values)
                    {
                        writer.WriteLine("{0}={1}", keyvalue.Key, keyvalue.Value);
                    }
                }
            }
        }        
    }
}
